package com.paas.form.controller;


import com.alibaba.fastjson.JSON;
import com.bpm.feign.model.BpmDeCategoryEntity;
import com.bpm.feign.model.BpmDeModelEntity;
import com.bpm.feign.model.ProcessCmd;
import com.bpm.feign.service.IBpmDeCategoryService;
import com.bpm.feign.service.IBpmDeModelService;
import com.bpm.feign.service.IBpmProcessInstanceService;
import com.paas.common.model.BaseUserInfo;
import com.paas.common.util.ListUtil;
import com.paas.common.util.StringUtil;
import com.paas.common.util.UniqueIdUtil;
import com.paas.common.web.SystemConst;
import com.paas.form.dto.FormViewResourceDto;
import com.paas.form.entity.*;
import com.paas.form.service.*;
import com.paas.form.vo.FormViewVo;
import com.publics.entity.UcResourcesEntity;
import com.publics.feign.service.IUcResourcesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.paas.common.util.BeanUtil;
import com.paas.common.model.RestResponse;
import com.paas.common.web.annotion.OperLog;
import com.paas.common.web.controller.BaseController;
import com.paas.common.web.oper.OprLogConstant;

@RestController
@RequestMapping(value = "/form/formViewResource")
@Api(description = "视图模块", tags = "")
public class FormViewResourceController extends BaseController {

    @Autowired
    public IFormViewResourceService formViewResourceService;

    @Autowired
    public IFormDefinitionService formDefinitionService;

    @Autowired
    public IFormViewPubService formViewPubService;

    @Autowired
    public IBpmProcessInstanceService bpmProcessInstanceService;

    @Autowired
    public IUcResourcesService ucResourcesService;

    @Autowired
    public IBpmDeCategoryService bpmDeCategoryService;

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(value = "保存信息", notes = "保存信息")
    @OperLog(operType = OprLogConstant.ADD, operModul = "", operDescribe = "-保存")
    public void save(@RequestBody FormViewResourceEntity formViewResourceEntity) throws ParseException {
        BaseUserInfo baseUserInfo = getUserInfo();
        if (BeanUtil.isNotEmpty(formViewResourceEntity)) {
            injectUpdateDataAuth(formViewResourceEntity);
            formViewResourceEntity.setStatus(SystemConst.NORMAL_STATUS);
            formViewResourceEntity.setModifyId(baseUserInfo.getUserId());
            formViewResourceEntity.setCreateId(baseUserInfo.getUserId());
            formViewResourceEntity.setModifyDate(new Date());
        }
        formViewResourceService.save(formViewResourceEntity);
    }

    @PostMapping(value = "/saveFormViewResource")
    @ApiOperation(value = "保存信息", notes = "保存信息")
    @ResponseBody
    public RestResponse saveFormViewResource(@RequestBody FormViewResourceDto<ProcessCmd> formViewResourceDto) {
        try {
            BaseUserInfo baseUserInfo = getUserInfo();
            // 菜单信息
            FormViewResourceEntity formViewResourceEntity = formViewResourceDto.getFormViewResourceEntity();
            // 流程信息
            ProcessCmd processCmd = formViewResourceDto.getProcessCmd();
            if (StringUtil.isEmpty(formViewResourceEntity.getId())) {
                formViewResourceEntity.setId(UniqueIdUtil.getIntGuid());
                if (BeanUtil.isNotEmpty(processCmd)) {
                    processCmd.setBusinessKey(formViewResourceEntity.getId());
                    processCmd.setData(JSON.toJSONString(formViewResourceEntity));
                    processCmd.setAppId(baseUserInfo.getAppId());
                    bpmProcessInstanceService.startProcessInstance(processCmd);
                }
                formViewResourceEntity.setStatus(SystemConst.NORMAL_STATUS);
                formViewResourceService.insert(formViewResourceEntity);
                //更新表单表状态
                formDefinitionService.updateFormStatus(formViewResourceEntity.getFormId(),FormDefinitionEntity.BIZ_STATUS_PUBLISHING);
            } else {
                processCmd.setToEditor(true);
                processCmd.setData(JSON.toJSONString(formViewResourceEntity));
                bpmProcessInstanceService.completeSubmitTask(processCmd);
                // 修改数据
                formViewResourceService.save(formViewResourceEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.error("保存失败");
        }
        return RestResponse.success();
    }

    @RequestMapping(value = "/saveBatch", method = RequestMethod.POST)
    @ApiOperation(value = "批量保存信息", notes = "批量保存信息")
    @OperLog(operType = OprLogConstant.UPDATE, operModul = "", operDescribe = "-批量保存修改")
    public void saveBatch(@RequestBody List<FormViewResourceEntity> list) throws ParseException {
        if (list != null && list.size() > 0) {
            injectUpdateDataAuth(list);
        }
        formViewResourceService.saveBatch(list);
    }

    @RequestMapping(value = "/delectById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id删除数据", notes = "根据Id删除数据")
    @OperLog(operType = OprLogConstant.DELETE, operModul = "", operDescribe = "-删除")
    public void delectById(String id) {
        if (null != id && !"".equals(id)) {
            FormViewResourceEntity formViewResourceEntity = new FormViewResourceEntity();
            injectUpdateDataAuth(formViewResourceEntity);
            formViewResourceEntity.setId(id);
            formViewResourceService.deleteByEntity(formViewResourceEntity);
        }
    }

    @RequestMapping(value = "/deleteBatchByIds", method = RequestMethod.POST)
    @ApiOperation(value = "根据Id批量删除数据", notes = "根据Id批量删除数据")
    @OperLog(operType = OprLogConstant.DELETE, operModul = "", operDescribe = "-批量删除")
    public void deleteBatchByIds(@RequestBody List<String> ids) {
        if (null != ids && ids.size() > 0) {
            FormViewResourceEntity formViewResourceEntity = new FormViewResourceEntity();
            injectUpdateDataAuth(formViewResourceEntity);
            //formViewResourceService.deleteBatchIds(ids);
            formViewResourceService.deleteBatchIdsWithPermission(ids, formViewResourceEntity);
        }
    }

    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id查询对象", notes = "根据Id查询对象")
    public FormViewResourceEntity queryById(String id) {
        FormViewResourceEntity formViewResourceEntity = null;
        if (StringUtil.isNotEmpty(id)) {
            formViewResourceEntity = formViewResourceService.getById(id);
            if (BeanUtil.isNotEmpty(formViewResourceEntity)) {
                UcResourcesEntity ucResourcesEntity = ucResourcesService.queryById(formViewResourceEntity.getParentId());
                if (BeanUtil.isNotEmpty(ucResourcesEntity)) {
                    formViewResourceEntity.setManuName(ucResourcesEntity.getShowName());
                }
            }
        }
        return formViewResourceEntity;
    }

    @RequestMapping(value = "/queryByViewFormId", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id查询对象", notes = "根据Id查询对象")
    public FormViewResourceEntity queryByViewFormId(String viewFormId) {
        FormViewResourceEntity formViewResourceEntity = formViewResourceService.queryByViewFormId(viewFormId);
        return formViewResourceEntity;
    }


    @RequestMapping(value = "/getFormViewResById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id查询对象", notes = "根据Id查询对象")
    public FormViewVo getFormViewResById(String id) {
        FormViewVo formViewVo = new FormViewVo();
        FormViewResourceEntity formViewResourceEntity = queryById(id);
        if (BeanUtil.isNotEmpty(formViewResourceEntity)) {
            UcResourcesEntity ucResourcesEntity = ucResourcesService.queryById(formViewResourceEntity.getParentId());
            if (BeanUtil.isNotEmpty(ucResourcesEntity)) {
                formViewResourceEntity.setManuName(ucResourcesEntity.getShowName());
            }
            FormDefinitionEntity formDefinitionEntity = formDefinitionService.getById(formViewResourceEntity.getFormId());
            if(BeanUtil.isNotEmpty(formDefinitionEntity)){
                FormViewPubEntity formViewPub =  formViewPubService.getById(formDefinitionEntity.getViewId());
                if("1".equals(formDefinitionEntity.getIsProcess())){
                    List<String> processIds = new ArrayList<>();
                    if(StringUtil.isNotEmpty(formDefinitionEntity.getApplyProcess())){
                        ListUtil.addUniqueValue(processIds,formDefinitionEntity.getApplyProcess());
                    }
                    if(StringUtil.isNotEmpty(formDefinitionEntity.getChangeProcess())){
                        ListUtil.addUniqueValue(processIds,formDefinitionEntity.getChangeProcess());
                    }
                    if(StringUtil.isNotEmpty(formDefinitionEntity.getDeleteProcess())){
                        ListUtil.addUniqueValue(processIds,formDefinitionEntity.getDeleteProcess());
                    }
                    if(StringUtil.isNotEmpty(formDefinitionEntity.getEnableProcess())){
                        ListUtil.addUniqueValue(processIds,formDefinitionEntity.getEnableProcess());
                    }
                    if(StringUtil.isNotEmpty(formDefinitionEntity.getStopProcess())){
                        ListUtil.addUniqueValue(processIds,formDefinitionEntity.getStopProcess());
                    }
                    //定义key为流程分类id,value为流程分类对象
                    Map<String, BpmDeCategoryEntity> bpmDeCategoryMap = new HashMap<String,BpmDeCategoryEntity>();
                    if(BeanUtil.isNotEmpty(processIds)){
                        List<BpmDeCategoryEntity> bpmDeCategoryList = bpmDeCategoryService.queryBatchByIds(processIds);
                        if(bpmDeCategoryList!=null){
                            bpmDeCategoryMap = bpmDeCategoryList.stream().collect(Collectors.toMap(BpmDeCategoryEntity::getId, item ->item));
                        }
                    }
                    if(bpmDeCategoryMap!=null){
                        //设置开启流程分类名称
                        if(bpmDeCategoryMap.containsKey(formDefinitionEntity.getApplyProcess())){
                            formDefinitionEntity.setApplyProcessName(bpmDeCategoryMap.get(formDefinitionEntity.getApplyProcess()).getCatgName());
                        }
                        if(bpmDeCategoryMap.containsKey(formDefinitionEntity.getChangeProcess())){
                            formDefinitionEntity.setChangeProcessName(bpmDeCategoryMap.get(formDefinitionEntity.getChangeProcess()).getCatgName());
                        }

                        if(bpmDeCategoryMap.containsKey(formDefinitionEntity.getDeleteProcess())){
                            formDefinitionEntity.setDeleteProcessName(bpmDeCategoryMap.get(formDefinitionEntity.getDeleteProcess()).getCatgName());
                        }

                        if(bpmDeCategoryMap.containsKey(formDefinitionEntity.getStopProcess())){
                            formDefinitionEntity.setStopProcessName(bpmDeCategoryMap.get(formDefinitionEntity.getStopProcess()).getCatgName());
                        }

                        if(bpmDeCategoryMap.containsKey(formDefinitionEntity.getEnableProcess())){
                            formDefinitionEntity.setEnableProcessName(bpmDeCategoryMap.get(formDefinitionEntity.getEnableProcess()).getCatgName());
                        }
                    }
                }
                formViewVo.setFormViewPub(formViewPub);
            }
            formViewVo.setFormViewResourceEntity(formViewResourceEntity);
            formViewVo.setFormDefinitionEntity(formDefinitionEntity);
        }
        return formViewVo;
    }


    @RequestMapping(value = "/queryBatchByIds", method = RequestMethod.POST)
    @ApiOperation(value = "根据Id查询对象列表", notes = "根据Id查询对象列表")
    public List<FormViewResourceEntity> queryBatchByIds(@RequestBody List<String> ids) {
        List<FormViewResourceEntity> list = formViewResourceService.getBatchByIds(ids);
        return list;
    }

    @RequestMapping(value = "/queryPage", method = RequestMethod.GET)
    @ApiOperation(value = "模板分页查询", notes = "模板分页查询")
    public IPage<FormViewResourceEntity> queryPage(FormViewResourceEntity formViewResourceEntity, Integer currentPage, Integer pageSize) {
        if (currentPage == null) {
            currentPage = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        injectCheckDataAuth(formViewResourceEntity);
        IPage<FormViewResourceEntity> pageBean = formViewResourceService.getPage(formViewResourceEntity, currentPage, pageSize);
        return pageBean;
    }

    @RequestMapping(value = "/queryList", method = RequestMethod.GET)
    @ApiOperation(value = "模板查询", notes = "模板查询")
    public List<FormViewResourceEntity> queryList(FormViewResourceEntity formViewResourceEntity) {
        injectCheckDataAuth(formViewResourceEntity);
        List<FormViewResourceEntity> list = formViewResourceService.getList(formViewResourceEntity);
        return list;
    }

    @RequestMapping(value = "/agreeApproval", method = RequestMethod.POST)
    @ApiOperation(value = "同意申请", notes = "同意申请")
    public RestResponse agreeApproval(String bussinessKey) {
        if (StringUtil.isNotEmpty(bussinessKey)) {
            FormViewResourceEntity formViewResourceEntity = formViewResourceService.getById(bussinessKey);
            if (BeanUtil.isNotEmpty(formViewResourceEntity)) {
                //更新表单表状态
                formDefinitionService.updateFormStatus(formViewResourceEntity.getFormId(),FormDefinitionEntity.BIZ_STATUS_PUBLISH);
                return RestResponse.success();
            }
        }
        return RestResponse.error();
    }

    @RequestMapping(value = "/refuseApproval", method = RequestMethod.POST)
    @ApiOperation(value = "反对", notes = "驳回申请")
    public RestResponse refuseApproval(String bussinessKey) {
        if (StringUtil.isNotEmpty(bussinessKey)) {
            FormViewResourceEntity formViewResourceEntity = formViewResourceService.getById(bussinessKey);
            if (BeanUtil.isNotEmpty(formViewResourceEntity)) {
                //数据反对
                formViewResourceEntity.setStatus("0");
                formViewResourceService.updateById(formViewResourceEntity);
                //更新表单表状态
                formDefinitionService.updateFormStatus(formViewResourceEntity.getFormId(),FormDefinitionEntity.BIZ_STATUS_APPROVAL);
                return RestResponse.success();
            }
        }
        return RestResponse.error();
    }
}